package com.hippo.tech;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionConfiguration;

import com.hippo.tech.framework.document.AppUser;
import com.hippo.tech.framework.mongorepository.AppUserRepository;
import com.hippo.tech.framework.service.UserService;
import com.hippo.tech.framework.value.UserValue;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring/appContext.xml"})
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
public class BaseTest {
	private Logger logger = Logger.getLogger(BaseTest.class);
	public static String TEST_USER_ID = "user@scr.com";
	public static String TEST_ADMIN_ID = "admin@admin.com";
	
	@Autowired
	UserService userService;
	
	@Autowired
	AppUserRepository appUserRepository;
	
	@Before
	public void setUp() throws Exception {
		System.out.println("Base TEST SETUP..");
		AppUser appUser = getTestUser();
		UserValue userValue = null;
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		grantedAuthorities.add(new SimpleGrantedAuthority(appUser.getAppRole().getName()));
		userValue = new UserValue(appUser.getId(), appUser.getUserId(), appUser.getPassword(), grantedAuthorities, appUser.getFirstName(), appUser.getLastName());

		UsernamePasswordAuthenticationToken ta = new UsernamePasswordAuthenticationToken(
				userValue, userValue.getPassword(), (Collection<? extends GrantedAuthority>) userValue.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(ta);
		logger.info("Testcase USER ID: " + userValue.getUserId());
	}
	
	protected AppUser getTestUser() {
		AppUser appUser = userService.getUserByUserID(TEST_USER_ID);
		return appUser;
	}
	
	protected String getTestUserPID() {
		return getTestUser().getId();
	}
	
	protected AppUser getTestAdmin() {
		AppUser appUser = userService.getUserByUserID(TEST_ADMIN_ID);
		return appUser;
	}
	
	public static int getRandomNumber() {
		return (int) (Math.random() * 1000);
	}

}
